<template>
    <div>
        <!-- 查询区域 -->
        <div class="card" style="margin-bottom:20px;">
            <el-input style="width:240px; margin-right:10px;" v-model="data.search.username" placeholder="请输入查询用户名"
                prefix-icon="Search"></el-input>
            <el-input style="width:240px; margin-right:10px;" v-model="data.search.nickName" placeholder="请输入查询昵称"
                prefix-icon="Search"></el-input>
            <el-button type="primary" @click="dataLoad">查询</el-button>
            <el-button type="warning" @click="reset">重置</el-button>
        </div>
        <!-- 操作区域 -->
        <div class="card" style="margin-bottom:10px;">
            <el-button type="primary" @click="handleAdd">新增</el-button>
            <el-button type="danger" @click="handleDeleteBatch">批量删除</el-button>
            <el-button type="success" @click="exportData">导出</el-button>
            <el-upload class="avatar-uploader" 
                action="http://localhost:8088/system/user/import"
                :show-file-list="false"
                :on-success="importData"
                style="display:inline-block;margin:0 10px;"
                >
                <el-button type="info">导入</el-button>
            </el-upload>
            
        </div>
        <!-- 数据表区域 -->
        <div class="card" style="margin-bottom:5px;">
            <!-- 数据表 -->
            <el-table :data="data.tableData" stripe @selection-change="handleSelection">
                <el-table-column type="selection" width="55"/>
                <el-table-column label="用户名" prop="username" />
                <el-table-column label="昵称" prop="nickName" />
                <el-table-column label="头像">
                    <template  #default="scope">
                        <img v-if="scope.row.avatar" :src="scope.row.avatar" style="display:block;width:40px;height:40px;border-radius:5px;"/>
                    </template>
                </el-table-column>
                <el-table-column label="性别" prop="sex" />
                <el-table-column label="身份证号" prop="idcard" />
                <el-table-column label="联系电话" prop="phone" />
                <el-table-column label="状态" prop="status" />
                <el-table-column label="所属部门" prop="orgId" />
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button link type="primary" :icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button link type="danger" :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页插件 -->
            <div style="margin-top:15px;">
                <el-pagination v-model:current-page="data.currentPage" v-model:page-size="data.pageSize"
                    :page-size="[10, 20, 50, 100]" 
                    layout="total,sizes,prev,pager,next,jumper" :total="data.total" @size-change="dataLoad"
                    @current-change="dataLoad" />
            </div>
        </div>
        
        <!-- 新增编辑弹出框 -->
        <el-dialog v-model="data.formVisible" title="新增用户" width="500" destroy-on-close>
            <el-form ref="formRef" :rules="data.rules" :model="data.form" style="margin:20px;" label-width="auto">
                <el-form-item label="头像" style="text-align: center;">
                    <el-upload class="avatar-uploader" 
                        action="http://localhost:8088/files/upload"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        >
                        <img v-if="data.form.avatar" :src="data.form.avatar" class="avatar"/>
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="data.form.username" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="昵称" prop="nickName">
                    <el-input v-model="data.form.nickName" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="部门">
                    <el-tree-select v-model="data.form.orgId" :data="data.orgList" check-strictly :render-after-expand="false" style="width: 240px" :props="{ children: 'children', label: 'name',value:'id' }"/>
                </el-form-item>
                <el-form-item label="性别">
                    <el-radio-group v-model="data.form.sex">
                        <el-radio value="1" label="男"></el-radio>
                        <el-radio value="2" label="女"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="身份证号">
                    <el-input v-model="data.form.idcard" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="联系电话">
                    <el-input v-model="data.form.phone" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="Email">
                    <el-input v-model="data.form.email" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="用户状态">
                    <el-radio-group v-model="data.form.status">
                        <el-radio value="0" label="正常"></el-radio>
                        <el-radio value="1" label="停用"></el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="data.formVisible = false">取消</el-button>
                    <el-button type="primary" @click="save">保存</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 新增编辑弹出框结束 -->
        
    </div>
</template>
<script setup>
import { reactive ,ref} from 'vue'
import { Search,Delete,Edit } from '@element-plus/icons-vue'
import request from "@/utils/request"
import { ElMessageBox } from 'element-plus'
const data = reactive({
    search: {username:null,nickName:null},//绑定查询参数
    tableData: [],
    currentPage: 1,
    pageSize: 10,
    total: 0,
    formVisible:false,
    form:{},
    ids:[],
    orgList:[],
    rules:{
        username:[
            {required:true,message:'请输入账号',trigger:'blur'}
        ],
        nickName:[
            {required:true,message:'请输入昵称',trigger:'blur'}
        ]
    }
})

request.post('/system/org/getTreeList').then(res=>{
    data.orgList = res.data
})

const exportData = ()=>{
    window.open("http://localhost:8088/system/user/export");
}

const importData=()=>{
    ElMessage.success("导入成功")
    dataLoad()
}

const formRef = ref()

//数据表数据加载函数
const dataLoad = ()=>{
    request.post("/system/user/getPage",{pageNum:data.currentPage,pageSize:data.pageSize,sysUser:data.search}).then(res=>{
        if(res.code===0){ //访问接口成功后绑定数据
            data.total = res.data.total
            data.tableData = res.data.list
        }else{
            ElMessage.error(res.message)
        }
        
    })
}
//执行加载数据函数
dataLoad()

//重置查询条件
const reset = ()=>{
    data.search.username = null
    data.search.nickName = null
    dataLoad()
}

//打开新增弹窗
const handleAdd=()=>{
    data.formVisible = true
    data.form={}
}

//打开编辑弹窗，并加载需要编辑数据
const handleEdit=(row)=>{
    data.form = JSON.parse(JSON.stringify(row))//深拷贝一个新的对象用于编辑，不影响现有的
    data.formVisible = true
}

//
const handleDelete=(row)=>{
    ElMessageBox.confirm("确认删除数据？",'删除确认',{type:'warning'}).then(()=>{
        request.delete('/system/user/deleteById',{
            params:{
                id:row.id
            }
        }).then(res=>{
            if(res.code===0){
                ElMessage.success("操作成功")
                dataLoad()
            }else{
                ElMessage.error(res.message)
            }
        })
    }).catch()
   
}

const save=()=>{
    formRef.value.validate((valid)=>{
        if(valid){
            data.form.id?update():add()
        }
    })
    
   
}
const add = ()=>{
    request.post('/system/user/save',data.form).then(res=>{
        if(res.code===0){
            data.formVisible=false
            ElMessage.success("操作成功")
            dataLoad()
        }else{
            ElMessage.error(res.message)
        }
    })
}

const update=()=>{
    request.put('/system/user/update',data.form).then(res=>{
        if(res.code===0){
            data.formVisible=false
            ElMessage.success("操作成功")
            dataLoad()
        }else{
            ElMessage.error(res.message)
        }
    })
}

const handleSelection=(rows)=>{
    console.log(rows)
    data.ids = rows.map(row => row.id)
    
    console.log(data.ids)
}

const handleDeleteBatch=()=>{
    if(data.ids.length===0){
        ElMessage.warning("请选择数据")
        return
    }
    ElMessageBox.confirm("确认删除数据？",'删除确认',{type:'warning'}).then(()=>{
        request.delete('/system/user/deleteByIds',{data:data.ids}).then(res=>{
            if(res.code===0){
                ElMessage.success('操作成功')
                dataLoad()
            }else{
                ElMessage.error(res.message)
            }
        })
    }).catch()
}

const handleAvatarSuccess= (res)=>{
    console.log(res.data)
    data.form.avatar=res.data;
}
</script>